package com.sourny.auth.task;


import com.sourny.encode.EncryptMD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import static com.ksudi.common.mvc.auth.consts.SecurityAuthConst.*;

/**
 * 定时刷新redis的token
 *
 * @author sourny.yang
 * @date 16:21 2018/6/7
 */
@Component
@EnableScheduling
public class TokenTask {
    private static Logger logger = LoggerFactory.getLogger(TokenTask.class);


    @Autowired
    private Environment environment;

    @Scheduled(fixedDelay = REFRESH_TIME)
    public void refreshToken() {
        String time = System.currentTimeMillis() + "";
        String token = EncryptMD5Util.encryptMD5twice(time);
        String key = AUTH_TOKEN + token;
        String value = environment.getProperty("spring.cloud.client.ip-address") + ":" + environment.getProperty("server.port") + "/" + environment.getProperty("spring.application.name") + ";time:" + time;
        CacheUtils.getCache(SECURITY_AUTH_STORE_REGION_KEY).put(key, value, EFFECTIVE_TIME);
        System.setProperty(AUTH_TOKEN, token);
        logger.info("refreshToken key:{}", key);
    }

    public static String getToken() {
        return System.getProperty(AUTH_TOKEN);
    }

    public static boolean checkToken(String key) {
        logger.info("checkToken key:{}", key);
        if (StringUtils.isNotBlank(key)) {
            Object value = CacheUtils.getCache(SECURITY_AUTH_STORE_REGION_KEY).get(AUTH_TOKEN + key);
            if (null != value) {
                logger.info("checkToken true value:{}", value);
                return true;
            }
        }
        return false;
    }

}
